package cn.shuangliang.contract.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sessionFactory;

    private static ThreadLocal<SqlSession> local=new ThreadLocal<>();
    static {
        try {
            String fileName = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(fileName);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sessionFactory = builder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private MyBatisUtil() {

    }

    public static SqlSession get() {
        SqlSession s=local.get();
        if(s==null){
            s=sessionFactory.openSession();
            local.set(s);
        }
        return s;
    }
    @Deprecated
    public static void close(SqlSession s) {

        if (s != null) {
            s.commit();
            s.close();
        }
    }
    public static void close() {
        SqlSession s=local.get();
        if (s != null) {
            local.set(null);
            s.commit();
            s.close();
        }
    }

    public static void main(String[] args) {
        System.out.println(get());
    }
}
